package com.ruoyi.project.channel.businessInfo.service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.Md5Utils;
import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.framework.shiro.service.PasswordService;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.channel.businessInfoOrder.domain.BusinessInfoOrder;
import com.ruoyi.project.channel.businessInfoOrder.service.IBusinessInfoOrderService;
import com.ruoyi.project.channel.freezeInfo.domain.FreezeInfo;
import com.ruoyi.project.channel.freezeInfo.service.IFreezeInfoService;
import com.ruoyi.project.channel.payerInfo.domain.PayerInfo;
import com.ruoyi.project.channel.payerInfo.service.IPayerInfoService;
import com.ruoyi.project.channel.salesmanInfo.domain.SalesmanInfo;
import com.ruoyi.project.channel.salesmanInfo.service.ISalesmanInfoService;
import com.ruoyi.project.channel.smsInfo.service.ISmsInfoService;
import com.ruoyi.project.channel.userGoodsInfo.domain.UserGoodsInfo;
import com.ruoyi.project.channel.userGoodsInfo.service.IUserGoodsInfoService;
import com.ruoyi.project.channel.userLevelConfig.domain.UserLevelConfig;
import com.ruoyi.project.channel.userLevelConfig.service.IUserLevelConfigService;
import com.ruoyi.project.channel.vwBusinessCashStat.domain.VwBusinessCashStat;
import com.ruoyi.project.channel.vwBusinessCashStat.service.IVwBusinessCashStatService;
import com.ruoyi.project.channel.vwIncomeDayStat.domain.VwIncomeDayStat;
import com.ruoyi.project.channel.vwIncomeDayStat.service.IVwIncomeDayStatService;
import com.ruoyi.project.pay.InvitationCodeGenerator;
import com.ruoyi.project.system.config.service.IConfigService;
import com.ruoyi.project.system.user.domain.User;
import com.ruoyi.project.system.user.service.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import com.ruoyi.project.channel.businessInfo.mapper.BusinessInfoMapper;
import com.ruoyi.project.channel.businessInfo.domain.BusinessInfo;
import com.ruoyi.common.utils.text.Convert;
import org.springframework.web.client.RestTemplate;

/**
 * 商家 服务层实现
 *
 * @author zero
 * @date 2019-05-04
 */
@Service
public class BusinessInfoServiceImpl implements IBusinessInfoService {
    @Autowired
    private BusinessInfoMapper businessInfoMapper;
    @Autowired
    private PasswordService passwordService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IVwBusinessCashStatService vwBusinessCashStatService;
    @Autowired
    private IUserLevelConfigService userLevelConfigService;
    @Autowired
    private IVwIncomeDayStatService vwIncomeDayStatService;
    @Autowired
    private IFreezeInfoService freezeInfoService;
    @Autowired
    private IUserGoodsInfoService userGoodsInfoService;
    @Autowired
    private IConfigService configService;
    @Autowired
    private IPayerInfoService payerInfoService;
    @Autowired
    private InvitationCodeGenerator invitationCodeGenerator;
    @Autowired
    private IBusinessInfoOrderService businessInfoOrderService;
    @Autowired
    private ISalesmanInfoService salesmanInfoService;
    private static final Logger log = LoggerFactory.getLogger(BusinessInfoServiceImpl.class);


    /**
     * 查询商家信息
     *
     * @param businessId 商家ID
     * @return 商家信息
     */
    @Override
    public BusinessInfo selectBusinessInfoById(Long businessId) {
        return businessInfoMapper.selectBusinessInfoById(businessId);
    }

    /**
     * 查询商家信息
     *
     * @param userId 商家ID
     * @return 商家信息
     */
    public BusinessInfo selectBusinessInfoByUserId(Long userId) {
        return businessInfoMapper.selectBusinessInfoByUserId(userId);
    }

    /**
     * 查询商家列表
     *
     * @param businessInfo 商家信息
     * @return 商家集合
     */
    @Override
    public List<BusinessInfo> selectBusinessInfoList(BusinessInfo businessInfo) {
        return businessInfoMapper.selectBusinessInfoList(businessInfo);
    }

    @Override
    public String getAddress() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("businessId=88888888");
        String time = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        stringBuilder.append("&time=").append(time);
        stringBuilder.append("&").append("xksiekerhdk12shskdfje03943kdjdkJHJGJKHJHJHG");
        String sign = "";
        try {
            sign = Md5Utils.androidMD5(stringBuilder.toString());
            // 获取钱包地址
            RestTemplate restTemplate = new RestTemplate();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("businessId", "88888888");
            jsonObject.put("time", time);
            jsonObject.put("sign", sign);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
            HttpEntity<String> entity = new HttpEntity<String>(jsonObject.toJSONString(), headers);
            PayerInfo payerInfo = payerInfoService.selectPayerInfoById(12521L);
            JSONObject body = restTemplate.exchange(payerInfo.getAddressUrl(), HttpMethod.POST, entity, JSONObject.class).getBody();
            log.info("getAddressUrl:" + body.toJSONString());
            return body.getString("data");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 新增商家
     *
     * @param businessInfo 商家信息
     * @return 结果
     */
    @Override
    public int insertBusinessInfo(BusinessInfo businessInfo, User user) {
//        TimeZone timeZone = TimeZone.getTimeZone("GMT-5");
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        format.setTimeZone(timeZone);
        String time1 = format.format(date);
        format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 生成邀请码
        try {
            businessInfo.setCreateTime(format.parse(time1));
        } catch (ParseException error) {
        }
        if (businessInfo.getOrderPrice() == null) {
            // 真人
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("businessId=88888888");
            String time = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
            stringBuilder.append("&time=").append(time);
            stringBuilder.append("&").append("xksiekerhdk12shskdfje03943kdjdkJHJGJKHJHJHG");
            String address = getAddress();
            businessInfo.setBankNo(address);
        } else {
            // 假人的时候取业务员的地址
            String probation = configService.selectConfigByKey("unreal_wallet_address");
            SalesmanInfo salesmanInfo = salesmanInfoService.selectSalesmanInfoById(businessInfo.getRootUserId());
            if(salesmanInfo !=null && salesmanInfo.getAddress() !=null) {
                probation = salesmanInfo.getAddress();
            }
            businessInfo.setBankNo(probation);
        }


        businessInfo.setUpdateTime(businessInfo.getCreateTime());
        businessInfo.setInvitationCode(invitationCodeGenerator.generateUniqueCode());
        Calendar calendar1 = Calendar.getInstance();
        calendar1.setTime(businessInfo.getCreateTime());
        String probation = configService.selectConfigByKey("probation");
        calendar1.add(Calendar.DATE, Integer.valueOf(probation));

        businessInfo.setDueDate(calendar1.getTime());

        businessInfo.setBusinessId(user.getUserId());
        businessInfo.setSalt(user.getSalt());
        businessInfo.setStatus("0");
        businessInfo.setUserId(user.getUserId());
        businessInfo.setPayPwd(passwordService.encryptPassword(user.getLoginName(), businessInfo.getPayPwd(), businessInfo.getSalt()));

        // 如果
        String testCash = configService.selectConfigByKey("test_cash");
        String testCashDay = configService.selectConfigByKey("test_cash_day");
        FreezeInfo freezeInfo = new FreezeInfo();
        freezeInfo.setAmount(BigDecimal.valueOf(Double.valueOf(testCash)));
        freezeInfo.setRealAmount(freezeInfo.getAmount());
        freezeInfo.setStartTime(businessInfo.getCreateTime());

        Calendar calendar2 = Calendar.getInstance();
        calendar2.setTime(businessInfo.getCreateTime());
        calendar1.add(Calendar.HOUR, Integer.valueOf(testCashDay) * 24 + 1); // 时间到了删除数据
        freezeInfo.setEndTime(calendar1.getTime());
        freezeInfo.setFreezeDay(Integer.valueOf(testCashDay));
        freezeInfo.setFreezeType("1");
        freezeInfo.setUserId(user.getUserId());
//        freezeInfoService.insertFreezeInfo(freezeInfo);

        BusinessInfoOrder order = new BusinessInfoOrder();
        order.setUserId(businessInfo.getUserId());
        order.setOrderNum(0);
        order.setDaySum(0);
        order.setOrderTimes(0);
        order.setOrderPrice(BigDecimal.ZERO);
        order.setBatch("0");
        businessInfoOrderService.insertBusinessInfoOrder(order);
        return businessInfoMapper.insertBusinessInfo(businessInfo);
    }

    /**
     * 修改商家
     *
     * @param businessInfo 商家信息
     * @return 结果
     */
    @Override
    public int updateBusinessInfo(BusinessInfo businessInfo) {
        return businessInfoMapper.updateBusinessInfo(businessInfo);
    }

    /**
     * 修改商家
     *
     * @param id 商家信息
     * @return 结果
     */
    @Override
    public AjaxResult resetPayPwd(String id, String newPassword) {
        BusinessInfo businessInfo = businessInfoMapper.selectBusinessInfoByUserId((Long.valueOf(id)));
        User user = userService.selectUserById(businessInfo.getUserId());
        businessInfo.setPayPwd(passwordService.encryptPassword(user.getLoginName(), newPassword, businessInfo.getSalt()));
        businessInfoMapper.updateBusinessInfo(businessInfo);
        return AjaxResult.success("重置成功！");
    }

    /**
     * 删除商家对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteBusinessInfoByIds(String ids) {
        return businessInfoMapper.deleteBusinessInfoByIds(Convert.toStrArray(ids));
    }

    @Override
    public boolean matches(String password) {
        BusinessInfo businessInfo = selectBusinessInfoByUserId(ShiroUtils.getUserId());
        if (businessInfo == null) {
            return false;
        }

        String newPwd = passwordService.encryptPassword(ShiroUtils.getLoginName(), password, businessInfo.getSalt());
        if (businessInfo.getPayPwd().equals(newPwd)) {
            return true;
        }
        return false;
    }

    @Override

    public VwBusinessCashStat getMyClickUserAmountInfo() {
        User user = ShiroUtils.getSysUser();
        VwBusinessCashStat businessCashStat = vwBusinessCashStatService.selectVwBusinessCashStatById(user.getUserId());
        // 当前可做任务档位
        UserLevelConfig search = new UserLevelConfig();
//        search.getParams().put("cash", businessCashStat.getClickFrzzingCash());
        search.setUseStatus("0");
        List<UserLevelConfig> configs = userLevelConfigService.selectUserLevelConfigList(search);
        UserLevelConfig config = configs.get(0);
//        UserLevelConfig level0Config = configs.get(configs.size()-1);
        businessCashStat.setUserLevelConfig(config);
        // 佣金统计表
        VwIncomeDayStat vwIncomeDayStat = new VwIncomeDayStat();
        vwIncomeDayStat.setUserId(user.getUserId());
        vwIncomeDayStat.setUpdateTime(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        List<VwIncomeDayStat> list = vwIncomeDayStatService.selectVwIncomeDayStatList(vwIncomeDayStat);
        BusinessInfoOrder order = businessInfoOrderService.selectBusinessInfoOrderById(user.getUserId());
        if (order == null) {
            order = new BusinessInfoOrder();
            order.setOrderPrice(BigDecimal.ZERO); // 金额
            order.setUserId(user.getUserId());
            order.setOrderNum(0); // 卡第几单
            order.setOrderTimes(0); // 倍数
            order.setDaySum(0); // 当日已抢单数量
            order.setBatch("0");
        }
        int todayTaskNum = order.getDaySum(); // 今日已做任务数
        BigDecimal todayTaskCommission = BigDecimal.ZERO; // 今日任务佣金
        int todayClickNum = 0; // 今日已抢单数
        BigDecimal todayClickCommission = BigDecimal.ZERO; // 今日抢单佣金
        BigDecimal todayFirstIncome = BigDecimal.ZERO; // 今日抢单佣金
        BigDecimal todaySecondIncome = BigDecimal.ZERO; // 今日抢单佣金
        BigDecimal todayThirdIncome = BigDecimal.ZERO; // 今日抢单佣金
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getType().equals("3")) {
//                todayTaskNum = list.get(i).getTotal().intValue();
                todayTaskCommission = list.get(i).getIncome();
            } else if (list.get(i).getType().equals("1")) {
                todayClickNum = list.get(i).getTotal().intValue();
                todayClickCommission = list.get(i).getIncome();
            } else if (list.get(i).getType().equals("4")) {
                todayFirstIncome = list.get(i).getIncome();
//                todayFirstIncome = list.get(i).getFirstIncome();
//                todaySecondIncome = list.get(i).getSecondIncome();
//                todayThirdIncome = list.get(i).getThirdIncome();
            }
        }
        int todayRemainTaskNum = config.getTaskNum() - todayTaskNum; // 今日还可以做任务数

        UserGoodsInfo searchUserGoodsInfo = new UserGoodsInfo();
        searchUserGoodsInfo.setUserId(order.getUserId());
        searchUserGoodsInfo.setBatch(order.getBatch());
        List<UserGoodsInfo> userGoodsInfos = userGoodsInfoService.selectUserGoodsInfoList(searchUserGoodsInfo);
        BigDecimal curCommision = BigDecimal.ZERO;
        for (int i = 0; i < userGoodsInfos.size(); i++) {
            curCommision = curCommision.add(userGoodsInfos.get(i).getProfit());
        }
        if (curCommision.compareTo(BigDecimal.ZERO) > 0) {
            todayTaskCommission = curCommision;
        }
        // 今日做的任务金额和上限金额比较
//        BigDecimal upperCommission = businessCashStat.getClickFrzzingCash().multiply(config.getCommissionPercentDay());
        boolean canDoTask = false; // 可以做任务
//        if (upperCommission.compareTo(todayTaskCommission) == 1 && todayRemainTaskNum > 0) {
//            // 上限金额如果大于当前任务佣金 && 当日可做任务数> 0 则可以继续做任务
//            canDoTask = true;
//        }
//        if (todayRemainTaskNum > 0) {
//            // 当日可做任务数> 0 则可以继续做任务
//            canDoTask = true;
//        }
        // 如果有未付款的商品则不可以继续抢单
        UserGoodsInfo searchInfo = new UserGoodsInfo();
        searchInfo.setUserId(user.getUserId());
        searchInfo.setPayStatus("NO_COMMIT");
        List<UserGoodsInfo> infos = userGoodsInfoService.selectUserGoodsInfoList(searchInfo);
        if (infos.isEmpty() && todayRemainTaskNum > 0 && businessCashStat.getAmountSum().compareTo(new BigDecimal("5")) > 0) {
            canDoTask = true;
        }
        // 今日可抢单数》0 或者刚注册3天内的
//        String probation = configService.selectConfigByKey("probation");
//        long remainTime = user.getCreateTime().getTime() + Integer.parseInt(probation) * 24 * 60 * 60 * 1000 - System.currentTimeMillis();
//        log.info("remainTime:"+remainTime);
//        log.info("getLevelName:"+config.getLevelName());
        int billCountDay = config.getBillCoutDay();
//        if(remainTime <= 0 && config.getLevelName().equals("level0")){
//            // 过期且是级别0 则可抢单数设置为0
//            billCountDay = 0;
//            config.setBillCoutDay(billCountDay);
//            log.info("setBillCoutDay:"+billCountDay);
//        }else if(remainTime > 0 && !config.getLevelName().equals("level0")){
//                // 过期且是级别1 则可抢单数设置为0
//                billCountDay = billCountDay + level0Config.getBillCoutDay();
//            log.info("setBillCoutDay 未超过3天且是vip的:"+billCountDay);
//                config.setBillCoutDay(billCountDay);
//        }
        int todayRemainClickNum = billCountDay - todayClickNum; // 今日还可以抢单数
        if (todayRemainClickNum < 0) {
            todayRemainClickNum = 0;
        }
        businessCashStat.setTodayClickCommission(todayClickCommission);
        businessCashStat.setTodayTaskCommission(todayTaskCommission);
        businessCashStat.setTodayClickNum(todayClickNum);
        businessCashStat.setTodayRemainClickNum(todayRemainClickNum);
        businessCashStat.setTodayRemainTaskNum(todayRemainTaskNum);
        businessCashStat.setTodayTaskNum(todayTaskNum);
        businessCashStat.setCanDoTask(canDoTask);
        businessCashStat.setTodayFirstIncome(todayFirstIncome);
        businessCashStat.setTodaySecondIncome(todaySecondIncome);
        businessCashStat.setTodayThirdIncome(todayThirdIncome);
        return businessCashStat;
    }
}
